package cn.wzptsoft.mall.handler;

import cn.hutool.json.JSONUtil;
import cn.wzptsoft.mall.pojo.result.Result;
import jakarta.servlet.FilterChain;
import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import org.springframework.stereotype.Component;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import java.io.IOException;


@Component
public class FilterChainExceptionHandler extends OncePerRequestFilter {

    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain)
            throws ServletException, IOException {

        try {
            filterChain.doFilter(request, response);
        } catch (Exception e) {
            e.printStackTrace();
            response.setCharacterEncoding("UTF-8");
            response.setStatus(HttpServletResponse.SC_OK);
            response.setHeader("Content-Type","application/json; charset=utf-8");
            response.getWriter().println(
                    JSONUtil.toJsonStr(Result.error(-1,"FilterChainExceptionHandler异常处理器："+e.getMessage()))
            );
        }
    }
}
